package com.example.secondhandmall.fragment;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.secondhandmall.R;
import com.example.secondhandmall.activity.LoginActivity;
import com.example.secondhandmall.activity.SearchFailureActivity;
import com.example.secondhandmall.activity.SearchSuccessActivity;
import com.example.secondhandmall.adapter.HomeAdapter;
import com.example.secondhandmall.api.Api;
import com.example.secondhandmall.api.ApiConfig;
import com.example.secondhandmall.api.MyCallback;
import com.example.secondhandmall.entity.GoodsEntity;
import com.example.secondhandmall.entity.GoodsListResponse;
import com.example.secondhandmall.entity.PhotoEntity;
import com.example.secondhandmall.entity.SearchGoodsEntity;
import com.example.secondhandmall.entity.SearchListResponse;
import com.example.secondhandmall.util.StringUtils;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class HomeFragment extends BaseFragment {

    private String[] mTitles = {"全部", "鞋服", "数码", "洗护", "食品", "手机", "家具", "玩具", "其他"};

    private ArrayList<Fragment> mFragments = new ArrayList<>();

    private ViewPager viewPager;
    private SlidingTabLayout slidingTabLayout;
    private EditText etSearch;
    private Button btnSearch;

    private String imgurl1;
    private String imgurl2;

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        viewPager = mRootView.findViewById(R.id.fixedViewPager);
        slidingTabLayout = mRootView.findViewById(R.id.slidingTabLayout);
        etSearch = mRootView.findViewById(R.id.et_search);
        btnSearch = mRootView.findViewById(R.id.btn_search);
    }

    @Override
    protected void initData() {
//        showToast("333");//这里就不会重复执行

        for (String title : mTitles) {
            mFragments.add(GoodsFragment.newInstance(title));
        }
        viewPager.setOffscreenPageLimit(mFragments.size());
        viewPager.setAdapter(new HomeAdapter(getFragmentManager(), mTitles, mFragments));
        slidingTabLayout.setViewPager(viewPager);

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取搜索词
                String searchWord = etSearch.getText().toString();

                getSearchList(searchWord);
//                localSearchList(searchWord);
            }
        });
    }


//接口请求数据
    private void getSearchList(String searchWord) {
        String account = getStringFromSp("account");
        if (true) {//这里要改
            HashMap<String, Object> params = new HashMap<>();
//            params.put("account", account);
//            params.put("searchWord", searchWord);
            params.put("msg", searchWord);
            Api.config(ApiConfig.GOODS_LIST_SEARCH, params).getRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
//                    showToastSync(res);
                    System.out.println(res);
                    SearchListResponse searchListResponse = new Gson().fromJson(res, SearchListResponse.class);
                    if (searchListResponse != null && searchListResponse.getCode() == 200) {
                        List<SearchGoodsEntity> list = searchListResponse.getData();
                        for (int i = list.size() -1; i >= 0; i--) {
                            if (list.get(i).getDel() != 0)
                                list.remove(i);
                        }
                        if (list != null && list.size() > 0) {
                            //跳转并把list传进去
//                            navigateTo(SearchSuccessActivity.class, "success", (Serializable) list);
//                            showToastSync("搜索成功!");
                            HashMap<String,Object> success = new HashMap<>();
                            success.put("list",list);
                            success.put("searchWord",searchWord);
                            navigateTo(SearchSuccessActivity.class, "success",  success);
                            showToastSync("搜索成功！");
                        } else {
                            List<String> failure = new ArrayList<>();
                            failure.add("没有找到相关物品。");
                            failure.add(searchWord);
                            navigateTo(SearchFailureActivity.class, "failure", (Serializable) failure);
                            showToastSync("没有找到相关物品！");
//                            navigateTo(SearchFailureActivity.class, "failure", "没有找到有关 “" + searchWord + "” 的搜索结果。");
//                            showToastSync("没有找到相关物品!");
                        }
                    }
                }

                @Override
                public void onFailure(Exception e) {
//                    navigateTo(SearchFailureActivity.class, "failure", "请求失败！");
//                    showToastSync("请求失败！");
                    List<String> failure = new ArrayList<>();
                    failure.add("请求失败！");
                    failure.add(searchWord);
                    navigateTo(SearchFailureActivity.class, "failure", (Serializable) failure);
                    showToast("请求失败！");
                }
            });
        } else {
            navigateTo(LoginActivity.class);
            showToast("请先登录");
        }
    }

//本地模拟数据
    private void localSearchList(String searchWord) {
        imgurl1 = "https://img.alicdn.com/bao/uploaded/i1/2493965190/O1CN01j4ARKR1oD4GRsrc3r_!!0-item_pic.jpg_200x200q90.jpg_.webp";
        imgurl2 = "https://img.alicdn.com/bao/uploaded/i4/3937219703/O1CN01SDh3xv2LY1jeFgRYe_!!3937219703-0-C2M.jpg_200x200q90.jpg_.webp";

        List<SearchGoodsEntity> list = new ArrayList<>();

        Random random = new Random();//默认构造方法
        int k = random.nextInt(2);//随机成功失败，1成功0失败
        int j = random.nextInt(2);

        if (j == 0) {
            for (int i = 0; i < 8; i++) {
                SearchGoodsEntity searchGoodsEntity = new SearchGoodsEntity();
                searchGoodsEntity.setGoodsName("一次性口罩");
                searchGoodsEntity.setGoodsPrice(11.58);
                searchGoodsEntity.setUserName("万宝绿");
                List<PhotoEntity> photoEntities = new ArrayList<>();
                PhotoEntity photoEntity1 = new PhotoEntity();
                PhotoEntity photoEntity2 = new PhotoEntity();
                photoEntity1.setGoodsPhotoUrl(imgurl1);
                photoEntity2.setGoodsPhotoUrl(imgurl2);
                photoEntities.add(photoEntity1);
                photoEntities.add(photoEntity2);
//                searchGoodsEntity.setPhotoUrls(photoEntities);
                searchGoodsEntity.setUserPhoto(imgurl1);
                searchGoodsEntity.setUserPhoto(imgurl2);

//                searchGoodsEntity.setGoodsSignature("品牌名称：万宝绿\n" +
//                        "产品参数：\n" +
//                        "\n" +
//                        "品牌: 万宝绿型号: 525功能: 防晒 防雾霾 防尘 防二手烟 防汽车尾气 防异味颜色分类: 7年老店承诺【收藏+加购】享24小时快速发货? ?正常脸型建议M号 10个 透气白色M号（体验装） 30个 透气白色M号（一包30只）?推荐 60个 透气白色M号（实惠装） 90个 透气白色M号（多囤点更优惠）?推荐 10个 透气黑色M号（体验装） 30个 透气黑色M号（一包30只）?推荐 60个 透气黑色M号（实惠装） 90个 透气黑色M号（多囤点更优惠）?推荐 ?130斤以上或大脸建议L号大码 10个 透气白色L号（大码130斤以上） 30个 透气白色L号（大码大脸请选这个） 60个 透气白色L号（实惠装） 90个 透气白色L号（多囤点更优惠）?推荐 10个 透气黑色L号（大码130斤以上） 30个 透气黑色L号（大码大脸请选这个） 60个 透气黑色L号（实惠装） 90个 透气黑色L号（多囤点更优惠）?推荐 ?选择困难症请看这里 10个M号白色+10个M号黑色（混色款） 30个M号白色+30个M号黑色（混色款） 10个L号白色+10个L号黑色（混色款） 30个L号白色+30个L号黑色（混色款）是否进口: 国产生产企业: .货号: 525安全标准: T/GDBX 025-2020");
//                searchGoodsEntity.setGoodsAddress("广东深圳");
//                searchGoodsEntity.setIsCollect(false);

                list.add(searchGoodsEntity);
            }
        }

        if (k == 0) {
            if (list != null && list.size() > 0) {
                HashMap<String,Object> success = new HashMap<>();
                success.put("list",list);
                success.put("searchWord",searchWord);
                navigateTo(SearchSuccessActivity.class, "success",  success);
                showToast("搜索成功！");
            } else {
                List<String> failure = new ArrayList<>();
                failure.add("没有找到相关物品。");
                failure.add(searchWord);
                navigateTo(SearchFailureActivity.class, "failure", (Serializable) failure);
                showToast("没有找到相关物品！");
            }
        } else {
            List<String> failure = new ArrayList<>();
            failure.add("请求失败！");
            failure.add(searchWord);
            navigateTo(SearchFailureActivity.class, "failure", (Serializable) failure);
            showToast("请求失败！");
        }
    }
}